package guzb.cnblogs.security.industrydemo.auth.restful;

import com.fasterxml.jackson.databind.ObjectMapper;
import guzb.cnblogs.security.industrydemo.util.JsonResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前后端分离模式下的，权限校验失败后的处理方式
 */
public class MyUriAccessDeniedProcessingFilter extends OncePerRequestFilter {

    ObjectMapper objectMapper;

    public MyUriAccessDeniedProcessingFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (AccessDeniedException e) {
            if (isRestfullRequest(request)) {
                doRestfulAccessDeniedProcess(request, response);
            }else {
                throw e;
            }
        }
    }

    private void doRestfulAccessDeniedProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json; charset=utf-8");
        JsonResponse<String> responseBody = JsonResponse.err401("无权访问: " + request.getRequestURI());
        response.getWriter().write(objectMapper.writeValueAsString(responseBody));
    }

    // 判断是否是前后端分离的请求
    private boolean isRestfullRequest(HttpServletRequest request) {
        return request.getRequestURI().startsWith("/api/app/");
    }
}
